package com.harvest.scientific.ladder.page

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActLogBinding
import com.harvest.scientific.ladder.ext.asLifecycleOwner
import com.harvest.scientific.ladder.ext.launchOnMain
import com.harvest.scientific.ladder.page.ui.main.MainViewModel
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.ToastUtil
import com.harvest.scientific.ladder.util.VcUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch


class LoginActivity : BaActivity(), View.OnClickListener {

    private lateinit var binding: ActLogBinding
    private var isCanGetSms = true
    private var canNext = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActLogBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initArgs()
        initEvent()
        initTextChangedListener()
        initObserver()
    }

    private var fromType = -1
    val mainViewModel by viewModels<MainViewModel>()

    private fun initArgs() {
        intent?.let {
            fromType = it.getIntExtra(FROM_TYPE, -1)
        }
    }

    private fun initObserver() {
        appModel.loginSuc.observe(asLifecycleOwner) {
            if (it) {
                mainViewModel.queryInjurePacificChicken { res ->
                    var flag = 0
                    if (res != null) {
                        for (item in res) {
                            if (item.mostEndlessComfortableLightning != "0") {
                                flag = 1
                            }
                        }
                    }
                    LogUtils.d("login after flag $flag")
                    launchOnMain {

                        if (flag == 0) {
                            startActivity(Intent(this@LoginActivity, Info1Activity::class.java))
                        } else {
                            HomeActivity.jump(this@LoginActivity, fromType, res)
                        }
                        finish()
                    }
                }
            }
        }
    }

    private fun initEvent() {
        binding.tvGetSms.setOnClickListener(this)
        binding.tvLogin.setOnClickListener(this)
        binding.llBack.setOnClickListener(this)
    }

    private fun initTextChangedListener() {
        binding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etSms.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
//                if (s?.length == 4) {
//                    startLogin()
//                }
            }
        })
    }

    private fun checkNextStatus() {
        canNext = getNextStatus()
        if (canNext) {
            binding.tvLogin.setBackgroundResource(R.drawable.bg_comon_sure_26)
        } else {
            binding.tvLogin.setBackgroundResource(R.drawable.bg_comon_disable_sure_26)
        }
    }

    private fun getNextStatus(): Boolean {
        if (binding.etPhone.text.toString().trim().isEmpty()
            || binding.etSms.text.toString().trim().isEmpty()) {
            return false
        }
        return true
    }

    override fun onClick(v: View) {
        if (VcUtil.isFastDoubleClick(v)) {
            return
        }
        when(v) {
            binding.llBack -> {
                onBackPressed()
            }
            binding.tvLogin -> {
                if (binding.etPhone.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etSms.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                startLogin()
            }
            binding.tvGetSms -> {
                if (binding.etPhone.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_phone))
                    return
                }
                if (!isCanGetSms) {
                    return
                }
                appModel.developBothTraining(binding.etPhone.text.toString())
                val builder = SpannableStringBuilder()
                val firstContent = getString(R.string.log_6)
                val secondContent = " 60S"
                builder.append(firstContent)
                builder.append(secondContent)
                builder.setSpan(ForegroundColorSpan(resources.getColor(R.color.color_868DC7)),0, firstContent.length ,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                countDown(
                    timeMillis = 1000L,
                    time = 60,
                    start = {
                        isCanGetSms = false
                    },
                    end = {
                        isCanGetSms = true
                        binding.tvGetSms.text = getString(R.string.log_5)
                        binding.tvGetSms.setTextColor(resources.getColor(R.color.color_868DC7))
                    },
                    next = {
                        isCanGetSms = false
                        val value = if(it < 10) {
                            "0${it}S"
                        } else {
                            "${it}S"
                        }
                        builder.replace(firstContent.length + 1, builder.length, value)
                        builder.setSpan(ForegroundColorSpan(resources.getColor(R.color.color_ff00000)),
                            firstContent.length + 1 ,
                            builder.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                        binding.tvGetSms.text = builder
                    },
                    error = {
                        isCanGetSms = true
                        binding.tvGetSms.text = getString(R.string.log_4)
                    })
            }
        }
    }

    override fun onBackPressed() {
        FlowBus.post (FlowBusConstant.GO_HOME, Unit)
        super.onBackPressed()

    }

    private fun startLogin() {
        if (canNext) {
            appModel.supportGreyMember(
                binding.etPhone.text.toString(),
                binding.etSms.text.toString()
            )
        }
    }

    fun countDown(
        timeMillis: Long = 1000,//默认时间间隔 1 秒
        time: Int = 60,//默认时间为 3 秒
        start: (scope: CoroutineScope) -> Unit,
        end: () -> Unit,
        next: (time: Int) -> Unit,
        error: (msg: String?) -> Unit
    ) {
        lifecycleScope.launch {
            flow {
                (time downTo 1).forEach {
                    delay(timeMillis)
                    emit(it)
                }
            }.onStart {
                start(this@launch)
            }.onCompletion {
                end()
            }.catch {
                error(it.message)
            }.collect {
                next(it)
            }
        }
    }

    companion object {
        fun jump(context: Context, fromType: Int) {
            context.startActivity(Intent(context, LoginActivity::class.java).apply {
                putExtra(FROM_TYPE, fromType)
            })
        }
    }
}

const val FROM_TYPE = "from_type"